import React, { Component } from 'react'
import store from '../../../redux'
import Api from '../../../config/api'
import axios from 'axios'
import Com from '../../../common/common'

import Table from 'antd/lib/table'
import Button from 'antd/lib/button'
import Navbar from '../../../Component/navbar'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import Input from 'antd/lib/input'
import Select from 'antd/lib/select'
import DatePicker from 'antd/lib/date-picker'
import Form from 'antd/lib/form'
import message from 'antd/lib/message'
import Popconfirm from 'antd/lib/popconfirm'
import Modal from 'antd/lib/modal'

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;
const Option = Select.Option;
const FormItem = Form.Item;
const { TextArea } = Input;
const confirm = Modal.confirm;

let oper = null;

function formatDay(value) {
    if (parseInt(value, 10) < 10) {
        return '0' + value;
    }
    else {
        return value
    }
}

function getToday() {
    let now = new Date();
    let day, month, year;
    day = now.getDate();
    month = now.getMonth() + 1;
    year = now.getFullYear();
    return year + '-' + formatDay(month) + '-' + formatDay(day);
}

function getFullDay(year,month){
    let limit = 30;
    switch (month) {
        case '01':
        case '03':
        case '05':
        case '07':
        case '08':
        case '10':
        case '12':
          limit = 31;
          break;
        case '04':
        case '06':
        case '09':
        case '11':
          limit=30;
          break;
        case '02':
          limit = year% 4? 28 : 29;
          break;
        default:
          limit = 30;
      }
      return limit
}

function limitDate(data){
    const arr = data.split('-').map((item)=>{
        return parseInt(item,10)
    });
    const days = getFullDay(arr[0],arr[1]);
    if(arr[2]+6>days){
        if(arr[1] === 12){
            arr[0]+=1;
            arr[1]=1;
        }
        else{
            arr[1]+=1;
        }
        arr[2]=arr[2]+6-days;        
    }
    else{
        arr[2]+=7;
    }
    return arr.join('-')
}

function limitDate2(data){
    const arr = data.split('-').map((item)=>{
        return parseInt(item,10)
    });
    let days = 30;
    if(arr[1] === 1){
        days = getFullDay(arr[0]-1,12);
    }
    else{
        days = getFullDay(arr[0],arr[1]-1);
    }
    if(arr[2]-7<1){
        if(arr[1] === 1){
            arr[0]-=1;
            arr[1]=12;
        }
        else{
            arr[1]-=1;
        }
        arr[2]=arr[2]-6+days;        
    }
    else{
        arr[2]-=6;
    }
    return arr.join('-')
}

function limitDate3(data){
    const arr = data.split('-').map((item)=>{
        return parseInt(item,10)
    });
    const days = getFullDay(arr[0],arr[1]);
    if(arr[2]+1>days){
        if(arr[1] === 12){
            arr[0]+=1;
            arr[1]=1;
        }
        else{
            arr[1]+=1;
        }
        arr[2]=arr[2]+1-days;        
    }
    else{
        arr[2]+=1;
    }
    return arr.join('-')
}

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: getToday(),
            endDate: '',
            startMonent: null,
            endMoment: null,
            selectionNum: 0
        }
    }
    componentWillReceiveProps(nextprops) {
        this.setState({
            selectionNum: nextprops.selectionNum
        })
    }
    componentDidMount() {
        this.search();
        this.setState({
            startMoment: moment(getToday(), "YYYY-MM-DD")
        })
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment || current > moment(limitDate3(getToday()),"YYYY-MM-DD") || current < moment(limitDate2(getToday()),"YYYY-MM-DD")
        }
        else {
            return current > moment(getToday(),"YYYY-MM-DD") || current < moment(limitDate2(getToday()),"YYYY-MM-DD")
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment || current > moment(limitDate(this.state.startDate), "YYYY-MM-DD") || current> moment(limitDate3(getToday()),"YYYY-MM-DD")
        }
        else {
            return current > moment(limitDate3(getToday()),"YYYY-MM-DD") || current < moment(limitDate2(getToday()),"YYYY-MM-DD")
        }
    }
    openCan1(){
        setTimeout(()=>{
        const ele1 = document.getElementsByClassName('ant-calendar-input')[0];
        ele1.setAttribute('readOnly','readOnly');
        },200)
    }
    openCan2(){
        setTimeout(()=>{
        const ele1 = document.getElementsByClassName('ant-calendar-input')[0];
        ele1.setAttribute('readOnly','readOnly');
        },200)
    }
    search() {
        let obj = {
            batchId: this.patchInput.input.value,
            content: this.contentInput.input.value,
            account: this.accountInput.input.value,
            status: this.statusInput.rcSelect.state.value[0],
            startTime: this.state.startDate,
            endTime: this.state.endDate
        }
        this.props.search(obj)
    }
    pushMsg1() {
        this.props.pushMsg1();
    }
    pushMsg2() {
        this.props.pushMsg2();
    }
    render() {
        return (
            <Navbar ref={(item) => {oper=item}} className="account-operbar">
                <Form layout="inline">
                    <FormItem label="批次编号"><Input style={{ width: '150px' }} ref={(input) => { this.patchInput = input }} /></FormItem>
                    <FormItem label="账号"><Input style={{ width: '150px' }} ref={(input) => { this.accountInput = input }} /></FormItem>
                    <FormItem label="短信内容"><Input style={{ width: '150px' }} ref={(input) => { this.contentInput = input }} /></FormItem>                    
                    <FormItem label="状态">
                        <Select style={{width:'150px'}} ref={(input) => { this.statusInput = input }} defaultValue={1}>
                            <Option value={1}>审核中</Option>
                            <Option value={2}>审核通过</Option>
                            <Option value={3}>审核驳回</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" onOpenChange={this.openCan1} dropdownClassName="can1" allowClear={false} defaultValue={moment(this.state.startDate, "YYYY-MM-DD")} disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" onOpenChange={this.openCan2} dropdownClassName="can2" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                        <Button type="primary" style={{ marginLeft: '10px' }} onClick={this.pushMsg1.bind(this)}>{this.state.selectionNum ? `批量通过(${this.state.selectionNum})` : '批量通过'}</Button>
                        <Button type="danger" style={{ marginLeft: '10px' }} onClick={this.pushMsg2.bind(this)}>{this.state.selectionNum ? `批量驳回(${this.state.selectionNum})` : '批量驳回'}</Button>
                    </FormItem>
                </Form>
            </Navbar>
        )
    }
}

const ValidateOperbar = Form.create()(OperBar);

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 0,
            tableHeight: 300,
            tableData: this.props.tableData,
            currentPage: 1,
            showReModal:false,
            nowRow:'',
            selectKeys:[]
        }
    }
    componentDidMount() {
        setTimeout(() => {
            let operbarHeight = oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
    }
    componentWillReceiveProps(nextprops) {
        this.setState({
            tableData: nextprops.tableData,
            dataNum: nextprops.dataNum,
            currntPage: nextprops.currentPage,
        })
        if (nextprops.resetSelectionFlag) {
            this.resetSelection()
        }
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight = oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    approveOk(data){
        axios.post(Api['updateBatchAuditByBatchId']+`?batchIds=${data.batchId}&status=2`).then((res) => {
            if (res) {
                this.props.search();
                message.success(res.desc)
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    approveReject(data){
        this.setState({
            showReModal:true,
            nowRow:data
        })
    }
    handleReSure(){
        this.props.form.validateFields(['remark'], (err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                axios.post(Api['updateBatchAuditByBatchId']+`?batchIds=${this.state.nowRow.batchId}&status=3&reason=${data.remark}`).then((res) => {
                    if (res) {
                        this.props.search();
                        this.props.form.resetFields();
                        message.success(res.desc);
                        this.setState({
                            showReModal:false
                        })
                    }
                }).catch((error) => {
                    console.log(error)
                })
            }
        });
    }
    handleReCancel(){
        this.setState({
            showReModal:false
        })
    }
    selectTable(keys, items) {
        let ids = '';
        let idsArr = [];
        let num = items.length;
        this.setState({
            selectKeys: keys
        })
        items.forEach((item) => {
            idsArr.push(item.batchId);
        })
        ids = idsArr.join(',')
        this.props.setSelection(ids, num);
    }
    resetSelection() {
        this.setState({
            selectKeys: []
        })
        this.selectTable([], []);
    }
    render() {
        const columns = [
            { title: '批次编号', dataIndex: 'batchId', key: '1', width: 200 },
            { title: '账号', dataIndex: 'account', key: '2', width: 220 },
            { title: '手机号数量', dataIndex: 'phoneCount', key: '3', width: 120 },
            {
                title: '短信内容', key: '4', width: 400, render: (record) => {
                    return (
                        <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={record.content}>
                            <a>{record.contentAbb}</a>
                        </Popconfirm>
                    )
                }
            },
            {
                title: '状态', key: '8', width: 200, render(record) {
                    return <span style={{ color: record.status === 1 ? '#0000ff' : record.status === 2?'green':'red' }}>{record.status === 1 ? '审核中' : record.status === 2 ? '审核通过':'审核驳回'}</span>
                }
            },
            { title: '驳回原因', key: '9', width: 400 , render: (record) => {
                    return (
                        <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={record.reason}>
                            <a>{record.reasonAbb}</a>
                        </Popconfirm>
                    )
                }
            },
            { title: '提交时间', dataIndex: 'createTime', key: '10', width: 200 },
            { title: '审核人', dataIndex: 'auditAccount', key: '11', width: 150 },
            { title: '审核时间', dataIndex: 'updateTime', key: '12', width: 200 },
            { title: '请求IP', dataIndex: 'ip', key: '5', width: 150 },
            { title: '自定义参数', key: '6', width: 150,render: (record) => {
                    return (
                        <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={record.uid}>
                            <a>{record.uidAbb}</a>
                        </Popconfirm>
                    )
                }
            },
            { title: '回调地址', key: '7', width: 220 , render: (record) => {
                    return (
                        <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={record.notifyUrl}>
                            <a>{record.notifyUrlAbb}</a>
                        </Popconfirm>
                    )
                }
            },
            {
                title: '操作',
                key: 'operation',
                fixed:'right',
                width: 300,
                render: (record) => {
                        return record.status===1?
                        (<div>
                            <a onClick={this.approveOk.bind(this, record)}>审核通过</a>
                            <a style={{marginLeft:'10px'}} onClick={this.approveReject.bind(this, record)}>审核驳回</a>
                        </div>):null
                    }
            }]
            const { getFieldDecorator } = this.props.form;
            const formItemLayout = {
                labelCol: {
                    xs: { span: 24 },
                    sm: { span: 6 },
                },
                wrapperCol: {
                    xs: { span: 24 },
                    sm: { span: 18 },
                },
            };
        return (
            <div className="account-table" style={{ marginTop: '10px' }}>
                <Table title={(data) => { return '审核列表' }} rowSelection={{ fixed: true, onChange: this.selectTable.bind(this), selectedRowKeys: this.state.selectKeys,getCheckboxProps:record=>({disabled:record.status!==1}) }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ x: 3000, y: this.state.tableHeight}}></Table>
                 <Modal visible={this.state.showReModal} onCancel={this.handleReCancel.bind(this)} title="驳回" footer={[
                    <Button key="sure" type="primary" onClick={this.handleReSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleReCancel.bind(this)}>取消</Button>
                ]} >
                    <Form>
                        <FormItem label="驳回原因" {...formItemLayout}>
                            {getFieldDecorator('remark', { validateTrigger: 'onBlur', rules: [{ required: true, message: '必填' },{ max: 200, message: '200字以内' }] })(<TextArea rows={3} style={{ width: 300 }} />)}
                        </FormItem>
                    </Form>
                </Modal>
            </div >
        )
    }
}

const ValidateTable = Form.create()(Table1);

class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            totalNum: 0,
            tableData: [],
            searchParams: {},
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            loading: true,
            currentPage: 1,
            selectShow: false,
            selectionIds: '',
            showModal: false,
            selectionNum: '',
            feedData: [],
            resetSelectionFlag: false,
            showReModal:false
        }
    }
    setParams(obj) {
        let data = JSON.parse(JSON.stringify(obj));
        this.setState({
            searchParams: data,
        }, () => {
            this.search('btn');
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        axios.post(Api['getAuditBatchByParams'], data).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach((item, index) => {
                    item.key = index;
                    if (item.content) {
                        item.contentAbb = Com.abbrData(item.content, 20);
                    }
                    if (item.uid) {                    
                    item.uidAbb = Com.abbrData(item.uid, 20);
                    }
                    if (item.notifyUrl) {
                        item.notifyUrlAbb = Com.abbrData(item.notifyUrl, 20);
                    }
                    if (item.reason) {
                        item.reasonAbb = Com.abbrData(item.reason, 20);
                    }
                })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag') })
    }
    setSelection(selectionIds, selectionNum) {
        this.setState({
            selectionIds,
            selectionNum
        })
    }
    pushSelections1() {
        if (this.state.selectionIds) {
            let that = this;
            confirm({
                title: '通过',
                content: `您确定要通过这${this.state.selectionNum}条记录么？`,
                okText: '确定',
                okType: 'confirm',
                cancelText: '取消',
                onOk() {
                    that.setState({
                        loading: true
                    })
                    axios.post(Api['updateBatchAuditByBatchId']+`?batchIds=${that.state.selectionIds}&status=2`).then((res) => {
                        if (res) {
                            that.search();
                            message.success(res.desc);
                            that.setState({
                                resetSelectionFlag: true,
                                loading: false
                            }, () => {
                                that.setState({
                                    resetSelectionFlag: false
                                })
                            })
                        }
                    }).catch((error) => {
                        console.log(error)
                    })
                },
                onCancel() { },
            });
        }
        else {
            message.info('请至少选择一条');
        }
    }
    pushSelections2(){
        if (this.state.selectionIds) {
            this.setState({
                showReModal:true,
            })
        }
        else {
            message.info('请至少选择一条');
        }
    }
    handleReSure(){
        this.props.form.validateFields(['remark'], (err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                this.setState({
                    loading: true
                })
                axios.post(Api['updateBatchAuditByBatchId']+`?batchIds=${this.state.selectionIds}&status=3&reason=${data.remark}`).then((res) => {
                    if (res) {
                        this.search();
                        this.props.form.resetFields();
                        message.success(res.desc);
                        this.setState({
                            resetSelectionFlag: true,
                            loading: false,
                            showReModal:false,
                        }, () => {
                            this.setState({
                                resetSelectionFlag: false
                            })
                        })
                    }
                }).catch((error) => {
                    console.log(error)
                })
            }
        });
    }
    handleReCancel(){
        this.setState({
            showReModal:false
        })
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        return (
            <div>
                <ValidateOperbar search={this.setParams.bind(this)} selectionNum={this.state.selectionNum} pushMsg1={this.pushSelections1.bind(this)} pushMsg2={this.pushSelections2.bind(this)} />
                <Spin spinning={this.state.loading} indicator={antIcon}>
                    <ValidateTable
                        search={this.search.bind(this)}
                        tableData={this.state.tableData}
                        dataNum={this.state.totalNum}
                        currentPage={this.state.currentPage}
                        changePageSize={this.changePageSize.bind(this)}
                        changePage={this.changePage.bind(this)}
                        setSelection={this.setSelection.bind(this)}
                        resetSelectionFlag={this.state.resetSelectionFlag}
                    />
                </Spin>
                <Modal visible={this.state.showReModal} onCancel={this.handleReCancel.bind(this)} title="驳回" footer={[
                    <Button key="sure" type="primary" onClick={this.handleReSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleReCancel.bind(this)}>取消</Button>
                ]} >
                    <Form>
                        <FormItem label="驳回原因" {...formItemLayout}>
                            {getFieldDecorator('remark', { validateTrigger: 'onBlur', rules: [{ required: true, message: '必填' },{ max: 200, message: '200字以内' }] })(<TextArea rows={3} style={{ width: 300 }} />)}
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        )
    }
}

const ValidateBox = Form.create()(Box);

export default ValidateBox